package com.ruoyi.auth.controller

import com.ruoyi.auth.form.LoginBody
import com.ruoyi.auth.form.RegisterBody
import com.ruoyi.auth.service.SysLoginService
import com.ruoyi.common.core.domain.R
import com.ruoyi.common.core.utils.JwtUtils
import com.ruoyi.common.core.utils.StringUtils
import com.ruoyi.common.security.auth.AuthUtil
import com.ruoyi.common.security.service.TokenService
import com.ruoyi.common.security.utils.SecurityUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
class TokenController {
    @Autowired
    private lateinit var tokenService: TokenService

    @Autowired
    private lateinit var sysLoginService: SysLoginService

    @PostMapping("login")
    fun login(@RequestBody form: LoginBody): R<*> {
        // 用户登录
        val userInfo = sysLoginService.login(form.username, form.password)
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo))
    }

    @DeleteMapping("logout")
    fun logout(request: HttpServletRequest?): R<*> {
        val token = SecurityUtils.getToken(request)
        if (StringUtils.isNotEmpty(token)) {
            val username = JwtUtils.getUserName(token)
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token)
            // 记录用户退出日志
            sysLoginService.logout(username)
        }
        return R.ok<Any>()
    }

    @PostMapping("refresh")
    fun refresh(request: HttpServletRequest?): R<*> {
        val loginUser = tokenService.getLoginUser(request)
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser)
            return R.ok<Any>()
        }
        return R.ok<Any>()
    }

    @PostMapping("register")
    fun register(@RequestBody registerBody: RegisterBody): R<*> {
        // 用户注册
        sysLoginService.register(registerBody.username, registerBody.password)
        return R.ok<Any>()
    }
}